var tree;
var ds,grid;

var buildTree = function(){
    var root = new Ext.tree.AsyncTreeNode({
        id:'0',
        text:'模块功能树',
        expanded : true
    });
    tree = new Ext.tree.TreePanel({
        loader:new Ext.tree.TreeLoader({dataUrl:'module!getTrees.action?parent_id=0'}),
        root:root,
        renderTo:'tree',
        border:false,
        autoScroll:true
    });
    tree.on('click',function(node){
        node.expand();
        node.select();
        ds.load({params:{parent_id:node.id}});
        node.expand();
    });
    tree.on('beforeload',function(node){
        tree.loader.dataUrl = 'module!getTrees.action?parent_id='+node.id;
    });
    root.expand();
    root.select();
};

var buildGrid = function(){
    ds = new Ext.data.Store({
        proxy:new Ext.data.HttpProxy({url:'module!getChildren.action'}),
        reader:new Ext.data.JsonReader({idProperty: "module.id"},['module.id','module.name','module.position','module.funcUrl',{name: 'module.ifFunc', type: 'bool'}])
    });
    var checkColumn = new Ext.grid.CheckColumn({
    	header: '是否功能',
	    dataIndex: 'module.ifFunc',
	   	width : 80
    });
    grid = new Ext.grid.EditorGridPanel({
        store:ds,
        plugins:checkColumn,
        columns:[
            new Ext.grid.RowNumberer(),
            {header:'名称',width:150,sortable:true,dataIndex:'module.name',editor:new Ext.form.TextField()},
            {header:'排序',width:50,sortable:true,dataIndex:'module.position',editor:new Ext.form.NumberField()},
            checkColumn,
            {header:'URL',width:450,sortable:true,dataIndex:'module.funcUrl',editor:new Ext.form.TextField()}
        ],
        renderTo:'grid',
        border:true,
        clicksToEdit:2,
        selModel:new Ext.grid.RowSelectionModel()
    });
    
    ds.load({params:{parent_id:'0'}});
};

var buildLayout = function(){
    new Ext.Viewport({
        layout:'border',
        defaults:{border:false},
        items:[{
            region:'north',
            contentEl:'north-div',
            title:'模块设置',
            tbar:[{
                text:'新增',
                iconCls:'admin-tool-add',
                handler:createModule
            },'-',{
                text:'保存',
                iconCls:'admin-tool-save',
                handler:saveModule
            },'-',{
                text:'删除',
               iconCls:'admin-tool-delete',
                handler:destroyModule
            }]
        },{
            region:'west',
            width:380,
            split:true,
            autoScroll:true,
            items:tree
        },{
            region:'center',
            layout:'fit',
            items:grid
        }]
    });
};

var init = function(){
    buildTree();
    buildGrid();
  	buildLayout();
};

Ext.onReady(init);

var createModule = function(){
    var node = tree.getSelectionModel().getSelectedNode();
    if (node){
        Ext.Ajax.request({
            url:'module!create.action',
            params:{
                parent_id:node.id,
                'module.name':'新模块'
            },
            success:function(response){
                var data = Ext.util.JSON.decode(response.responseText);
                if (data.success){
                    node.appendChild(new Ext.tree.TreeNode({
                        id:data.id,
                        text:'新模块',
                        leaf:true
                    }));
                    node.getUI().removeClass('x-tree-node-leaf');
                    node.getUI().addClass('x-tree-node-expanded');
                    node.leaf = false;
                    node.expand();
                    ds.reload();
                }
                else{
                    Ext.MessageBox.alert('警告',data.msg);
                }
            }
        })
    }
};

var saveModule = function(){
	var records = ds.getModifiedRecords();
	for (var i = 0; i < records.length; i++) {
		var params = records[i].data;
    	if(tree.getSelectionModel().getSelectedNode().id>0)
    		params['module.parent.id'] = tree.getSelectionModel().getSelectedNode().id;
		
        Ext.Ajax.request({
            url:'module!update.action',
            params:params,
            method:'POST',
            success:function(response){
                var data = Ext.util.JSON.decode(response.responseText);
                var r = ds.getById(data.id);
				r.commit();
                var node = tree.getSelectionModel().getSelectedNode().findChild('id',data.id);
                if (node){
                    node.setText(data.name);
                }
            }
        });
	}
};
var destroyModule = function(){

	var rows = grid.getSelectionModel().getSelections();
	var node = tree.getSelectionModel().getSelectedNode();
	
	if (rows.length == 0 && (!node || node.id =='0')){
		Ext.Msg.alert("提示", "您还没有选择任何模块！");
		return;
	}

	if (rows.length == 0 && !node.isLeaf()) {
		Ext.Msg.alert("提示", "您选中的模块有子模块，请先删除子模块！");
		return;
	}

	var ids = [];
	if (rows.length > 0){
		for (var i = 0; i < rows.length; i++) {
			ids.push(rows[i].data['module.id']);
		}
	}
	else{
		ids.push(node.id);
	}
	

	Ext.Ajax.request({
		url:'module!delete.action',
		method:'POST',
		params:{'ids':ids},
		success:function(response){
			var data = Ext.util.JSON.decode(response.responseText);
			var rows = grid.getSelectionModel().getSelections();
			if (data.success){
				for(var i = 0 ;i < ids.length; i++){
					var id = ids[i];
					var snode = tree.getSelectionModel().getSelectedNode();
					if (snode.id == id){  //当前树节点是要删除的节点
						snode.remove();
		            }
		            else{ //通过id查找子节点
		            	var node = snode.findChild('id',id);
		                node.remove();
		            }
				}
						                
		        ds.reload();
		        Ext.MessageBox.alert('警告','删除模块资料完成。');
	        }
			else{
	            Ext.MessageBox.alert('警告',data.msg);
			}
		}
	});
}
